﻿using Common.Service;
using Common.Views;
using Core.Domain.Model;
using NSBus.Dto.Commands;
using NServiceBus;
using Sanelib.Common.Helpers;
using Sanelib.DataOperation;
using Sanelib.DataView;
using Sanelib.Dto.Enumerations;

namespace NSBus.Server.CommandHandlers
{
    public class ResetPasswordHandler : MessageHandler<ResetPasswordCommand>
    {
        private readonly IRepository<Member> _memberRepository;
        private readonly ICryptographer _cryptographer;
        private readonly IViewRepository<TempleteView> _templeteViewRepository;
        public IBus Bus { get; set; }

        public ResetPasswordHandler(IRepository<Member> memberRepository, ICryptographer cryptographer, IViewRepository<TempleteView> templeteViewRepository, IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {
            _memberRepository = memberRepository;
            _cryptographer = cryptographer;
            _templeteViewRepository = templeteViewRepository;
        }

        public override void HandleMessage(ResetPasswordCommand message)
        {
            var token = _cryptographer.ComputeHash(message.Token);
            var member = _memberRepository.GetByKey(Property.Of<Member>(x => x.PasswordRetrievalToken), token);

            if (member == null) return;

            var salt = _cryptographer.CreateSalt();
            var hash = _cryptographer.ComputeHash(message.NewPassword + salt);

            member.PasswordHash = hash;
            member.PasswordSalt = salt;
            member.LastPasswordChangedDate = SystemTime.Now();
            member.PasswordRetrievalToken = "";
            member.PasswordRetrievalTokenExpirationDate = null;
            member.FailedAttemptCount = 0;
            member.UserStatus = UserStatus.Active;

            _memberRepository.Update(member);

            var messageBody = _templeteViewRepository.GetByKey(Property.Of<TempleteView>(x => x.Name), "Reset Password").Value;

            Bus.SendLocal<SendEmailCommand>(m =>
            {
                m.To = member.Email;
                m.Subject = "Sanelib Password Reset Notification";
                m.MessageBody = string.Format(messageBody, member.Email);
            });
        }
    }
}
